import React from 'react';
import styles from './index.less';
import { Button, Select, Input, Tree, Popconfirm } from 'antd';
import { useSetState } from 'ahooks';
import { groupBy } from 'lodash';
import {
  PlusOutlined,
  DeleteOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
} from '@/utils/antdIcons';
// components
import { TRDefault, TRMessage } from '@/components';
// api
import { HttpCode } from '@/utils/contacts';
import { mqttCentre } from '@/utils/mqttCentre';
import {
  getCounterPartyList,
  addCounterParty,
  delCounterPartyAndContracts,
} from '../../../services';

// 对手方自定义treeSelect组件
export default ({ onChange = () => {}, provinceId, buttonPermissions }) => {
  /** data */
  const addIptRef = React.useRef();
  const treeRef = React.useRef();
  const ALL_KEY = '__all__';
  const SYSTEM_KEY = '__system__';
  const CUSTOM_KEY = '__costom__';
  // 按钮权限
  const canAdd = buttonPermissions.some((x) => x.menuCode === 'addCounterParty');
  const canDel = buttonPermissions.some((x) => x.menuCode === 'delCounterPartyAndContracts');
  const [addData, setAddData] = React.useState(null); // mq增删数据
  const [delData, setDelData] = React.useState(null); // mq增删数据
  const [state, setState] = useSetState({
    loading: false,
    open: false, // 自定义下拉展示
    searchValue: '', // 自定义搜索
    expandedKeys: [SYSTEM_KEY, CUSTOM_KEY], // 自定义展开
    // 对手方
    list: [],
    selected: null,
    // 新建
    addValue: '',
    isAdding: false,
    operating: false, // 操作防抖
  });

  /** lifetimes */
  React.useEffect(() => {
    bindMq();
    return () => {
      unbindMq();
    };
  }, []);

  React.useEffect(() => {
    fetchList(provinceId);
  }, [provinceId]);

  React.useEffect(() => {
    // 改变选中
    if (!state.selected?.key) return;
    const { key, title } = state.selected;
    if (key === ALL_KEY) {
      const sysIds = state.list.filter((x) => x.counterpartyType === 'system').map((x) => x.key);
      onChange?.(sysIds, '全部系统对手方');
    } else {
      onChange?.([key], title);
    }
    setState({
      open: false,
    });
  }, [state.selected?.key]);

  React.useEffect(() => {
    addItem(addData);
  }, [addData]);

  React.useEffect(() => {
    delItem(delData);
  }, [delData]);

  /** methods */
  // 对手方-订阅增删
  const bindMq = () => {
    mqttCentre.subscribe('COUNTERPARTY_ADD', `counterparty_add_${CLIENT_ENV}`, (data) => {
      setAddData(data);
    });
    mqttCentre.subscribe('COUNTERPARTY_DEL', `counterparty_del_${CLIENT_ENV}`, (data) => {
      setDelData(data);
    });
  };
  const unbindMq = () => {
    mqttCentre.unsubscribe('COUNTERPARTY_ADD');
    mqttCentre.unsubscribe('COUNTERPARTY_DEL');
  };

  const addItem = (data) => {
    const temp = data?.[provinceId];
    if (!temp) return;
    temp.title = temp.counterpartyName;
    temp.key = temp.counterpartyId;
    setState({
      list: [...state.list, temp],
    });
  };

  const delItem = (data) => {
    const id = data?.counterPartyId;
    if (!id) return;
    let { list, selected } = state;
    const i = list.findIndex((x) => x.counterpartyId === id);
    i > -1 && list.splice(i, 1);
    if (id === selected?.key) {
      selected = { key: ALL_KEY };
    }
    setState({
      list: [...list],
      selected,
    });
  };

  // 对手方请求
  const fetchList = async (id) => {
    if (!id) return;
    setState({ loading: true });
    const res = await getCounterPartyList(id);
    setState({ loading: false });
    const _list = res?.results || [];
    // antd版本低，不支持fieldNames
    _list.map((x) => {
      x.title = x.counterpartyName;
      x.key = x.counterpartyId;
    });
    setState({
      list: _list,
      selected: { key: ALL_KEY },
    });
  };

  // 删除对手方
  const handleDelete = async ({ counterpartyId, id }) => {
    if (!canDel) return TRMessage.info('请联系管理员获取相关权限');
    const res = await delCounterPartyAndContracts({ counterpartyId, id });
    if (res?.statusCode === HttpCode.SUCCESS) {
      fetchList(provinceId);
      TRMessage.success('删除成功');
    } else {
      TRMessage.error(res?.message || '删除失败');
    }
  };

  const handleAdd = async () => {
    // 新建
    if (state.operating) return;
    const counterPartyName = state.addValue;
    if (!counterPartyName) return TRMessage.error('对手方名称必须填写');
    setState({ operating: true });
    const res = await addCounterParty({
      counterPartyName,
      provinceId,
    });
    setState({ operating: false });
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('添加成功');
      fetchList(provinceId);
      setState({ isAdding: false, addValue: '' });
    } else {
      TRMessage.error(res?.message || '添加失败');
    }
  };

  const openSelect = () => {
    const key = state.selected?.key;
    setState({ open: true });
    key && treeRef.current?.scrollTo({ key });
  };

  const closeSelect = () => {
    setState({
      open: false,
      isAdding: false,
      addValue: '',
    });
  };

  /** render */
  const treeData = React.useMemo(() => {
    // 对手方分组
    const _list = !state.searchValue
      ? state.list
      : state.list.filter((x) => x.counterpartyName.indexOf(state.searchValue) > -1);
    const groups = groupBy(_list, 'counterpartyType');
    return [
      { key: ALL_KEY, title: <div className={styles.groupname}>全部系统对手方</div> },
      {
        key: SYSTEM_KEY,
        title: <div className={styles.groupname}>系统对手方</div>,
        selectable: false,
        children: groups?.system || [],
      },
      {
        key: CUSTOM_KEY,
        title: <div className={styles.groupname}>自定义对手方</div>,
        selectable: false,
        children: (groups?.custom || []).map((x) => ({
          ...x,
          title: (
            <>
              {x.title}
              {x.counterpartyId !== '0' && (
                <Popconfirm
                  placement="rightTop"
                  title={'删除对手方公司操作会将关联合约一并删除！'}
                  onConfirm={(e) => {
                    e.stopPropagation();
                    handleDelete(x);
                  }}
                  onCancel={(e) => e.stopPropagation()}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    className={styles.btn_del}
                    type="link"
                    icon={<DeleteOutlined />}
                    onClick={(e) => e.stopPropagation()}
                  />
                </Popconfirm>
              )}
            </>
          ),
        })),
      },
    ];
  }, [state.list, state.searchValue]);

  const _tree = () => {
    // 对手方树
    if (state.loading) return '正在加载...';
    if (!state.list?.length) return <TRDefault type="emptysm" />;
    return (
      <Tree
        ref={treeRef}
        className={styles.my_tree}
        treeData={treeData}
        height={300}
        blockNode
        defaultExpandAll
        selectable
        selectedKeys={[state.selected?.key]}
        onSelect={(__, e) => {
          setState({
            selected: { ...e.node },
          });
        }}
      />
    );
  };

  return (
    <>
      <Select
        style={{ width: '100%', fontSize: 12 }}
        dropdownStyle={{ padding: 0 }}
        value={state.selected?.counterpartyName || '全部系统对手方'}
        dropdownMatchSelectWidth={200}
        bordered={false}
        showSearch
        onSearch={(v) => setState({ searchValue: v })}
        open={state.open}
        onClick={openSelect}
        dropdownRender={() => (
          <div
            onMouseDown={(e) => {
              e.preventDefault();
              e.stopPropagation();
            }}
          >
            {_tree()}
            {/* 新建 自定义对手方 */}
            <div className={styles.add}>
              {state.isAdding ? (
                <div className={styles.add_input}>
                  <Input
                    ref={addIptRef}
                    value={state.addValue}
                    onChange={(e) => setState({ addValue: e.target.value })}
                    bordered={false}
                    placeholder="请输入不超过15个字"
                    maxLength={30}
                    suffix={
                      <>
                        <CheckCircleFilled style={{ color: '#27AE60' }} onClick={handleAdd} />
                        <CloseCircleFilled
                          style={{ color: '#BDBDBD', marginLeft: 4 }}
                          onClick={() => setState({ isAdding: false, addValue: '' })}
                        />
                      </>
                    }
                  />
                </div>
              ) : (
                <Button
                  block
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    if (!canAdd) return TRMessage.info('请联系管理员获取相关权限');
                    setState({ isAdding: true });
                    setTimeout(() => {
                      addIptRef.current?.focus();
                    }, 0);
                  }}
                >
                  新建
                </Button>
              )}
            </div>
          </div>
        )}
      />
      {state.open && <div className={styles.mask} onClick={closeSelect} />}
    </>
  );
};
